﻿using System.Collections.Generic;
using Godot;

namespace kemocard.Scripts.Common;

public partial class SaveData : GodotObject
{
    public Godot.Collections.Dictionary<string, bool> GlobalBoolSave { get; private set; } = new();
    public Godot.Collections.Dictionary<string, double> GlobalNumberSave { get; private set; } = new();
    public Godot.Collections.Dictionary<string, string> GlobalStringSave { get; private set; } = new();
    public Godot.Collections.Dictionary<string, GodotObject> GlobalObjectSave { get; private set; } = new();
}

public static class SaveMgr
{
    private const string SaveFilePath = "user://save.sav";
    private static SaveData _currentSave;

    public static void SaveGame()
    {
        using var file = FileAccess.Open(SaveFilePath, FileAccess.ModeFlags.Write);
        file.StoreString(Json.Stringify(_currentSave));
    }

    public static void LoadGame()
    {
        using var file = FileAccess.Open(SaveFilePath, FileAccess.ModeFlags.Read);
        _currentSave = file == null ? new SaveData() : Json.ParseString(file.GetAsText()).As<SaveData>();
    }

    public static void SetGlobalBool(string key, bool value)
    {
        _currentSave.GlobalBoolSave[key] = value;
        SaveGame();
    }

    public static bool GetGlobalBool(string key)
    {
        return _currentSave.GlobalBoolSave.GetValueOrDefault(key, false);
    }

    public static void SetGlobalNumber(string key, double value)
    {
        _currentSave.GlobalNumberSave[key] = value;
        SaveGame();
    }

    public static double GetGlobalNumber(string key)
    {
        return _currentSave.GlobalNumberSave.GetValueOrDefault(key, 0);
    }

    public static void SetGlobalString(string key, string value)
    {
        _currentSave.GlobalStringSave[key] = value;
        SaveGame();
    }

    public static string GetGlobalString(string key)
    {
        return _currentSave.GlobalStringSave.GetValueOrDefault(key, "");
    }

    public static void SetGlobalObject(string key, GodotObject obj)
    {
        _currentSave.GlobalObjectSave[key] = obj;
        SaveGame();
    }

    public static GodotObject GetGlobalObject(string key)
    {
        return _currentSave.GlobalObjectSave.GetValueOrDefault(key, null);
    }
}